package org.renhui.network;

import android.text.TextUtils;

import java.net.MalformedURLException;
import java.net.URL;

/**
 *  Url 解析工具类
 *  参照 http://developer.android.com/reference/java/net/URL.html
 *
 * Created by RenHui on 15-2-6.
 */
public class UrlTranslator {
    private URL mUrl;
    
    private String mProtocol;   // URL请求协议
    private String mUserInfo;   // URL上的username:password
    private String mHost;       // 主机
    private int mPort;          // 端口号
    private String mFile;       // 文件
    
    // 构造函数，用于检查用户的URL是否符合规范，并将URL解析
    public UrlTranslator(String url) throws MalformedURLException{
        this.mUrl = new URL(url);
        
        this.mProtocol = this.mUrl.getProtocol();
        this.mUserInfo = this.mUrl.getUserInfo();
        this.mHost = this.mUrl.getHost();
        this.mPort = this.mUrl.getPort();
        this.mFile = this.mUrl.getFile();
    }
    
    public String host() {
        return this.mHost;
    }
    
    public String translate(String host) {
        String url = this.mProtocol + "://";
        
        if (!TextUtils.isEmpty(this.mUserInfo)) {
            url += (this.mUserInfo + "@");
        }
        
        url += host;
        if (this.mPort > 0) {
            url += (":" + this.mPort);
        }
        
        url += this.mFile;
        return url;
    }
}
